package cn.smbms.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.RoleService;
import cn.smbms.service.UserService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;

@Controller
@RequestMapping(value="/sys/users")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@Resource
	private RoleService roleService;
	
	@RequestMapping("/userlist")
	public String getAllUser(Model model,
			@RequestParam(value="queryname",required=false) String queryUserName,
			@RequestParam(value="queryUserRole",required=false) String queryUserRole,
			@RequestParam(value="pageIndex",required=false) String pageIndex){
		
		
		int  _queryUserRole=0;
		List<User> userList=null;
		//设置页面容量
		int pageSize=Constants.pageSize;
		//当前页码
		int currentPageNo=1;
		//如果查询的用户名==null
		if(queryUserName==null) {
			//那么用户名=""
			queryUserName="";
		}
		//如果用户角色不等于null并且用户角色不是""
		if(queryUserRole !=null && !queryUserRole.equals("")) {
			//那么用户角色=此处将queryUserRole字符串转换为整型并存储到int类型的_queryUserRole中
			_queryUserRole=Integer.parseInt(queryUserRole);
		}
		
		if(pageIndex!=null) {
			try {
			currentPageNo=Integer.parseInt(pageIndex);
			}catch(NumberFormatException e) {
				return "redirect:/syserror";
			}
		}
		//总数量
		int totalCount=userService.getUserCount(queryUserName, _queryUserRole);
		//总页数
		PageSupport pages=new PageSupport();
		pages.setCurrentPageNo(currentPageNo);
		pages.setPageSize(pageSize);
		pages.setTotalCount(totalCount);
		int totalPageCount = pages.getTotalCount();
		if(totalCount%pageSize!=0 || totalCount<pageSize){
			totalPageCount=totalCount/pageSize+1;
		}else {
			totalPageCount=totalCount/pageSize;
		}
		//控制首页和尾页
		if(currentPageNo<1) {
			currentPageNo=1;
		}else if(currentPageNo>totalPageCount) {
			currentPageNo=totalPageCount;
		}
		userList=userService.getUserList(queryUserName, _queryUserRole, currentPageNo, pageSize);
		model.addAttribute("userList", userList);
		List<Role> roleList=null;
		roleList=roleService.getRoleList();
		model.addAttribute("roleList", roleList);
		model.addAttribute("queryUserName", queryUserName);
		model.addAttribute("queryUserRole", queryUserRole);
		model.addAttribute("totalPageCount", totalPageCount);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("currentPageNo", currentPageNo);
		return "userlist";
	}
	
	@RequestMapping(value="/usermodify")
	public String updateUser(@ModelAttribute("user")User user,HttpSession session) {
		
		int i=userService.updateUser(user);
		if(i>0) {
			return "redirect:/sys/users/userlist";
		}else {
			return "usermodify";
		}
	}
	@RequestMapping(value="usermodify/{id}")
	public String update(@PathVariable("id")int id,Model model) {
		User user=userService.byidgetUser(id);
		
		model.addAttribute(user);
		return "usermodify";
		
	}
	
	@RequestMapping(value="/getRoleList",produces="application/json;charset=UTF-8")
	@ResponseBody
	public Object getRoleList() {
		List<Role> list=roleService.getRoleList();
		
		
		return JSONArray.toJSONString(list);
		
		
	}
	//删除供应商
		@RequestMapping(value="/deluser.json",method=RequestMethod.GET)
		@ResponseBody
		public Object deleteUser(@RequestParam(value="id") String id){
			
			HashMap<String, String> resultMap = new HashMap<String, String>();
			if(!StringUtils.isNullOrEmpty(id)){
				boolean flag = false;
				boolean	fla = false ;
				try {
				fla = userService.deleteUser(Integer.parseInt(id));
				} catch (NumberFormatException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(flag!=fla){//删除成功
					resultMap.put("delResult", "true");
				}else{//删除失败
					resultMap.put("delResult", "false");
				}
			}else{
				resultMap.put("delResult", "notexit");
			}
			return JSONArray.toJSONString(resultMap);
		}
	/*@RequestMapping(value="/deluser.json")
	public String deleteUser(@RequestParam("id")int id) {
		int i=userService.deleteUser(id);
		if(i>0) {
			return "redirect:/sys/users/userlist";
		}else {
			return "error";
		}
		

	}*/
	@RequestMapping("/userview/{id}")
	public String viewUser(@PathVariable("id")int id,Model model) {
		User user=userService.byidgetUser(id);
		model.addAttribute(user);
		return "userview";
		
	}
	
	
	@RequestMapping(value="/useradd",method=RequestMethod.POST)
	public String addUser(User user){
		int i=userService.addUser(user);
		if(i>0) {
			return "redirect:/sys/users/userlist";
		}else{
			return "useradd";
		}
		
	}
	
	
	@RequestMapping("useraddj") 
	public String addUserj() {
		
		return "useradd";
		
	}
	//用户编码的校验
		@RequestMapping(value="ucexist.json",produces= {"application/json;charset=UTF-8"})
		@ResponseBody
		public Object ucexist(@RequestParam("userCode")String userCode,HttpSession session) {
			Object o=session.getAttribute(Constants.USER_SESSION);
			String userCode2=((User)o).getUserCode();
			Map<String, String> resultMap = new HashMap<String, String>();
			
			if(StringUtils.isNullOrEmpty(userCode)){//旧密码输入为空
				resultMap.put("result", "exist");
			}else{  
				String userCode3 = ((User)o).getUserCode();
				if(userCode.equals(userCode2)){
					resultMap.put("userCode", "exist");
				}else{//重名
					resultMap.put("userCode", "noexist");
				}
			}
			
			return JSONArray.toJSON(resultMap);
		}
	
}
